<script setup lang="ts">
import { ref, onBeforeUnmount, onMounted } from 'vue'
import { GetIndividualOrganizerActivities } from '@/api/organizer'
import { GetIndividualOrganizerActivitiesResponse } from '@/types/organizer'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import * as signalR from '@microsoft/signalr'

//志愿活动数据
let tableData = ref<Array<GetIndividualOrganizerActivitiesResponse>>()
//获取用户创建的志愿活动
const myActivities = await GetIndividualOrganizerActivities()
tableData = ref(myActivities.data)

//跳转到详情页面
let router = useRouter()
const handleClick = (row: GetIndividualOrganizerActivitiesResponse) => {
  console.log(row)
  router.push({ path: '/OrganizerHome', query: { myOrganizedActivityId: row.activityId } })
}
//刷新重新获取数据
const Refresh = async () => {
  tableData.value = (await GetIndividualOrganizerActivities()).data
}
//用户数据
const userStore = useUserStore()
//启动连接
const server = new signalR.HubConnectionBuilder()
  .withUrl('http://localhost:900/VoluntaryIdentity/Signalr/Hubs/ChatRoomHub', {
    // 设置是否跳过提升
    skipNegotiation: true,
    // 设置传输类型
    transport: signalR.HttpTransportType.WebSockets,
    accessTokenFactory: () => userStore.token
  }) // 设置日志级别
  .configureLogging(signalR.LogLevel.Information)
  // 构建HubConnection
  .build()

// 发送消息出现异常
let errorOccur = false

onMounted(async () => {
  await server.start()
  server.on('sendPrivateMessage', (msg) => {
    errorOccur = true
    ElMessage.warning(msg)
  })
})

//发送消息输入框
const sendMessageBox = ref(false)
const sendMessageBoxTitle = ref('')
const sendMessageForm = ref({ message: '' })
let sendMessageActivityId = 0
//signalr发送消息
const openSendMessageBox = (row: GetIndividualOrganizerActivitiesResponse) => {
  sendMessageBoxTitle.value = `请输入要向参加${row.activityName}活动的志愿者发送的消息`
  sendMessageActivityId = row.activityId
  sendMessageBox.value = true
}
const sendMessage = async () => {
  if (sendMessageForm.value.message.length === 0) {
    ElMessage.warning('消息不能为空')
    return
  }
  await server.invoke('SendMessageForActivity', sendMessageForm.value.message, sendMessageActivityId)
  sendMessageBox.value = false
  if (!errorOccur) {
    ElMessage.success('消息发送成功')
  }
}

//获取活动状态函数
const getActivityStatus = (row: GetIndividualOrganizerActivitiesResponse): string => {
  if (dayjs(row.activityStartTime) > dayjs()) {
    return '准备中'
  } else if (dayjs(row.activityStartTime) <= dayjs() && dayjs(row.activityEndTime) >= dayjs()) {
    return '进行中'
  } else {
    return '已结束'
  }
}

//给表格每一列设置颜色
const tableRowClassName = ({ row }: { row: GetIndividualOrganizerActivitiesResponse }): string => {
  if (row.activityCompleted) {
    return 'warning-row'
  } else if (dayjs(row.activityStartTime) > dayjs()) {
    console.log(row.activityName)
    return 'success-row'
  } else if (dayjs(row.activityStartTime) < dayjs() && dayjs(row.activityEndTime) > dayjs()) {
    return 'primary-row'
  } else {
    return 'danger-row'
  }
}

onBeforeUnmount(() => {
  server.stop()
})
</script>

<template>
  <el-container>
    <el-header>
      <el-row style="background-color: #ffffff">
        <el-col :span="6">
          <el-statistic title="创建的全部志愿活动" :value="myActivities.data.length"></el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="正在准备的志愿活动"
            :value="myActivities.data.filter((item) => !item.activityCompleted && dayjs(item.activityStartTime) > dayjs()).length"
          >
            <template #suffix>/{{ myActivities.data.length }}</template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="正在进行的志愿活动"
            :value="
              myActivities.data.filter((item) => !item.activityCompleted && dayjs(item.activityStartTime) < dayjs() && dayjs(item.activityEndTime) > dayjs())
                .length
            "
          >
            <template #suffix>/{{ myActivities.data.length }}</template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="已结束的志愿活动"
            :value="myActivities.data.filter((item) => item.activityCompleted || dayjs(item.activityEndTime) < dayjs()).length"
          >
            <template #suffix>/{{ myActivities.data.length }}</template>
          </el-statistic>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-table :data="tableData" style="width: 100%; height: 100%" v-if="tableData?.length !== 0" :row-class-name="tableRowClassName">
        <el-table-column label="创建日期">
          <template #default="scope">
            {{ dayjs(scope.row.activityEnlistTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column prop="activityName" label="名称" />
        <el-table-column prop="activityType" label="活动类型" />
        <el-table-column label="活动状态">
          <template #default="scope">
            {{ getActivityStatus(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="activityAddress" label="活动地址" />
        <el-table-column fixed="right" label="操作">
          <template #default="scoped">
            <el-button link type="primary" size="small" @click="handleClick(scoped.row)">查看详情</el-button>
            <el-button link type="primary" size="small" @click="openSendMessageBox(scoped.row)">发送消息</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="你还没有创建任何活动">
        <el-button type="primary" @click="Refresh">刷新</el-button>
      </el-empty>
      <el-dialog v-model="sendMessageBox" :title="sendMessageBoxTitle">
        <el-form :model="sendMessageForm">
          <el-form-item label="消息">
            <el-input v-model="sendMessageForm.message" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="sendMessageBox = false">取消</el-button>
            <el-button type="primary" @click="sendMessage"> 发送 </el-button>
          </span>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<style scoped>
.el-col {
  text-align: center;
}

.el-table >>> .warning-row {
  background: rgb(244, 234, 215);
}

.el-table >>> .success-row {
  background: rgb(214, 243, 203);
}

.el-table >>> .primary-row {
  background: rgb(209, 241, 247);
}

.el-table >>> .danger-row {
  background-color: rgb(245, 223, 214);
}
</style>
